<template>
  <el-container class="page-container">
    <el-header>
      <el-page-header :content="mode === 'add' ? '添加角色' : '编辑角色'" @back="$router.back()" />
    </el-header>
    <el-container>
      <el-aside width="220px">
        <el-steps direction="vertical" :active="activeStep" finish-status="finish" process-status="finish">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </el-aside>
      <el-main>
        <!-- 标题 -->
        <div class="title">{{ title[activeStep] }}</div>
        <!-- 角色信息 -->
        <el-form v-show="activeStep === 0" ref="roleFormRef" :model="roleForm" :rules="roleRules" class="role-info" size="medium" label-position="right" label-width="100px">
          <el-form-item label="角色名称：" prop="roleName">
            <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述：" prop="remark">
            <el-input v-model="roleForm.remark" type="textarea" placeholder="请输入角色描述" :rows="4" />
          </el-form-item>
        </el-form>
        <!-- 权限信息 -->
        <div v-show="activeStep === 1" class="permission-container">
          <div v-for="(item, index) in permissionTree" :key="item.id" class="permission-item">
            <!-- 标题 -->
            <div class="permission-title">{{ item.title }}</div>
            <!-- 功能权限树 -->
            <el-tree
              :ref="`permissionTreeRef${index}`"
              :data="item.children"
              show-checkbox
              node-key="id"
              :props="{ label: 'title' }"
              default-expand-all
            />
          </div>
        </div>
        <!-- 检查并完成 -->
        <el-descriptions v-show="activeStep === 2" :column="1">
          <el-descriptions-item label="角色名称">{{ roleForm.roleName }}</el-descriptions-item>
          <el-descriptions-item label="角色描述">{{ roleForm.remark }}</el-descriptions-item>
          <el-descriptions-item label="角色权限">
            <div class="permission-container">
              <div v-for="(item, index) in disabledPermissionTree" :key="item.id" class="permission-item">
                <!-- 标题 -->
                <div class="permission-title">{{ item.title }}</div>
                <!-- 功能权限树 -->
                <el-tree
                  :ref="`disPermissionTreeRef${index}`"
                  :data="item.children"
                  show-checkbox
                  node-key="id"
                  :props="{ label: 'title' }"
                  default-expand-all
                />
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-main>
    </el-container>
    <!-- 底部操作按钮 -->
    <el-footer>
      <el-button v-show="activeStep > 0" size="medium" @click="onPrevStep">上一步</el-button>
      <el-button v-show="activeStep < 2" type="primary" size="medium" @click="onNextStep">下一步</el-button>
      <el-button v-show="activeStep === 2" type="primary" size="medium" @click="onSaveRole">保存</el-button>
    </el-footer>
  </el-container>
</template>

<script>
import { getPermissionTreeAPI, addRoleAPI, updateRoleAPI, getRoleDetailsAPI } from '@/api/system/role'

import { addDisabledToTree } from '@/utils/tools'

export default {
  name: 'RoleEditor',
  data() {
    return {
      activeStep: 0, // 当前步骤
      title: {
        0: '角色信息',
        1: '权限信息',
        2: '检查并完成'
      },
      // 角色信息表单数据
      roleForm: {
        roleName: '', // 角色名称
        remark: '' // 角色描述
      },
      // 角色信息表单验证规则
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      permissionTree: [], // 功能权限树
      disabledPermissionTree: [], // 带禁用的功能权限树
      checkedKeysList: [] // 权限树中被选中节点的 key 列表
    }
  },
  computed: {
    // 当前编辑器页面是新增还是编辑
    mode() {
      return this.$route.query.mode
    },
    // 当编辑器页面是编辑时，被编辑角色的ID
    roleId() {
      return this.$route.query.roleId
    }
  },
  created() {
    // 获取功能权限树
    this.getPermissionTree()
    if (this.mode === 'edit') {
      // 获取角色详情
      this.getRoleDetails()
    }
  },
  methods: {
    // 上一步
    onPrevStep() {
      if (this.activeStep > 0) {
        this.activeStep--
      }
    },
    // 下一步
    onNextStep() {
      if (this.activeStep < 2) {
        // 如果是第一步，则验证表单
        if (this.activeStep === 0) {
          this.$refs.roleFormRef.validate(valid => {
            if (valid) {
              // 如果是编辑角色，则设置功能权限选中状态
              console.log(this.checkedKeysList)
              if (this.mode === 'edit') {
                this.checkedKeysList.forEach((item, index) => {
                  this.$refs[`permissionTreeRef${index}`][0].setCheckedKeys(item)
                })
              }
              this.activeStep++
            }
          })
        } else if (this.activeStep === 1) {
          // 获取权限树中被选中的节点的 key(权限id)，包含父节点的id
          this.checkedKeysList = this.permissionTree.map((item, index) => {
            return this.$refs[`permissionTreeRef${index}`][0].getCheckedNodes(false, true).map(node => node.id)
          })
          // this.checkedKeysList = this.permissionTree.map((item, index) => {
          //   return this.$refs[`permissionTreeRef${index}`][0].getCheckedKeys(true)
          // })
          console.log(this.checkedKeysList)
          // 判断是否选择了至少一项权限
          if (this.checkedKeysList.every(item => item.length === 0)) {
            this.$message.error('请至少选择一项！')
          } else {
            // 跳转下一页
            this.activeStep++
            // 设置下一页功能权限选中状态
            this.disabledPermissionTree.forEach((item, index) => {
              this.$refs[`disPermissionTreeRef${index}`][0].setCheckedKeys(this.checkedKeysList[index])
            })
            this.checkedKeysList.forEach((item, index) => {
              if (item.length > 0) {
                item.unshift(2000 + index)
              }
            })
            console.log(this.checkedKeysList)
          }
        } else {
          this.activeStep++
        }
      }
    },
    // 获取功能权限树
    async getPermissionTree() {
      this.permissionTree = await getPermissionTreeAPI()
      const res = await getPermissionTreeAPI()
      console.log(this.permissionTree)
      this.disabledPermissionTree = addDisabledToTree(res)
    },
    // 查询当前角色详情
    async getRoleDetails() {
      // 获取角色详情
      const details = await getRoleDetailsAPI(this.roleId)
      this.roleForm = { roleName: details.roleName,
        remark: details.remark, roleId: details.roleId }
      this.checkedKeysList = details.perms
    },
    // 保存角色
    async onSaveRole() {
      const data = {
        ...this.roleForm,
        perms: this.checkedKeysList
      }
      if (this.mode === 'add') {
        await addRoleAPI(data)
        this.$message.success('添加成功')
      } else {
        await updateRoleAPI(data)
        this.$message.success('修改成功')
      }
      this.$router.push('/sys/role')
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  .el-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;
    border-bottom: 1px solid #eee;

    ::v-deep .el-page-header {
      .el-page-header__title {
        font-size: 16px;
        font-weight: 600;
        color: #444;
      }

      .el-page-header__content {
        font-size: 16px;
        font-weight: 600;
        color: #444;
      }
    }
  }
  .el-container {
    height: calc(100% - 156px);
    .el-aside {
      padding-top: 30px;
      .el-steps {
        height: 200px;
        margin-left: 20px;
      }
    }
    .el-main {
      width: 100%;
      padding-top: 30px;
      border-left: 1px solid #eee;
      .title {
        height: 20px;
        margin-bottom: 40px;
        font-weight: bold;
        color: #444;
      }
      .role-info {
        margin: 0 60px 0 80px;
        .el-input {
          margin-bottom: 20px;
        }
      }
      .permission-container {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        .permission-item {
          padding: 20px;
          min-width: 0;
          border: 1px solid #eee;
          border-top: none;
          border-right: none;
          .permission-title {
            width: 100%;
            padding: 10px 0;
            text-align: center;
            font-size: 14px;
            background-color: #f6f7f8;
          }
          ::v-deep .el-tree {
            .el-tree-node {
              white-space: normal;
              .el-tree-node__content {
                height: auto;
                margin-top: 4px;
                // line-height: 24px;
                align-items: baseline;
              }
            }
          }
        }
        .permission-item:first-child, .permission-item:nth-child(4) {
          border-left: none;
        }
        .permission-item:nth-child(4), .permission-item:nth-child(5) {
          border-bottom: none;
        }
      }
      .el-descriptions {
        ::v-deep .el-checkbox__inner {
          border-color: #bbb;
          background-color: #eee;
        }
        .el-checkbox__inner::after {
          border-color: #777;
        }
      }
    }
  }
  .el-footer {
    display: flex;
    height: auto !important;
    justify-content: center;
    gap: 20px;
    padding: 25px 0;
    el-button {
      height: 36px;
    }
  }
}
</style>
